package services;

import domain.entities.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nico
 * Date: 06/08/12
 * Time: 18:54
 * To change this template use File | Settings | File Templates.
 */
@Service
public class AddressService {

    private CountriesDAO countriesDAO;
    private CitiesDAO citiesDAO;
    private RegionsDAO regionsDAO;

    public AddressService() {
    }

    @Autowired
    public AddressService(CountriesDAO countriesDAO, CitiesDAO citiesDAO, RegionsDAO regionsDAO) {
        this.countriesDAO = countriesDAO;
        this.citiesDAO = citiesDAO;
        this.regionsDAO = regionsDAO;
    }

    public List<Countries> getCountries(){
        return countriesDAO.findAll();
    }

    public List<Regions> getRegions(Short id){
        List<Regions> list = regionsDAO.findByCountry("countryId", id);
        Collections.sort(list);
        return list;
    }

    public String getCountryCode(Short id){
        Countries pais = countriesDAO.findById(id);
        if(pais != null)
            return pais.getCountryCode();
        return null;
    }

    public List<Cities> getCities(Short regionId) {
        List<Cities> cities = citiesDAO.findByRegion("regionId", regionId);
        Collections.sort(cities);
        return cities;
    }

    public Countries getCountryByName(String countryName){
        return countriesDAO.findByCountry(countryName).get(0);
    }

    public Regions getRegionByName(String regionName, String countryId){
        return regionsDAO.findByRegionAndCountry(regionName, countryId);
    }

    public Cities getCityByName(String cityName, String regionId, String countryId){
        return citiesDAO.findByRegionAndCountry(cityName, regionId, countryId);
    }

    public void checkCity(String cityName, String regionName, String countryName){
        Countries c = this.getCountryByName(countryName);
        Regions r = this.getRegionByName(regionName, c.getCountryId().toString());
        if (!citiesDAO.findByCity(cityName, r.getRegionId().toString())){
            citiesDAO.attachDirty(new Cities(r.getCountries().toString(), r.getRegionId().toString(), cityName, new Float(0), new Float(0), ""));
        }
        return ;
    }
}
